<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport ( 'joomla.filesystem.file' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JobBoardModelJAResumes extends JModel {
	var $_table;
	var $_pagination;
	var $_fieldList = null;
	var $_searchparams;
	var $_fieldListEdit;
	var $_table_name = 'ja_resumes';
	
	/**
	 * Return the query is used to retrive all row from database
	 * @return string The query is used 
	 */
	function getItems($where_more = '', $limit, $limitstart, $feature_module = false) {
		global $mainframe, $jbconfig, $option;
		
		// Get the page/component configuration
		$params = &$mainframe->getParams ();
		
		$db = JFactory::getDBO ();

		$request = JRequest::get('request');
		JRequest::set($request, 'post');
		$filter_field_keys = array();
		if(isset($request['category']) && !is_array($request['category']) ){
			$request['category'] = str_replace( "--", "&amp;", $request['category']);
			if( strpos($request['category'], "+") == 0 )
				$request['category'] = trim($request['category']);
		}
		if(isset($request['location_id']) && !is_array($request['location_id']) ){       
			$request['location_id'] = str_replace( "--", "&amp;", $request['location_id']);		
			if( strpos($request['location_id'], "+") == 0 )
				$request['location_id'] = trim($request['location_id']);
		}
		if($request){
			$filter_field_keys = array_keys($request);
		}
		
		$search = JRequest::getVar ( 'resume_search', '' );
		$search = trim(JString::strtolower ( $search ));
		
		$user = JFactory::getUser ();
		$this->getFieldList ( ' and fl.admin_only=0 ' );
		$this->getEditFieldList ( ' and f.frontend_hidden=0' );
				
		$filter_order = JRequest::getVar('filter_order', "a.id");
		$filter_order_Dir = JRequest::getVar('filter_order_Dir', "DESC");
		
		// just in case filter_order get's messed up
		$join 	= '';
		$order 	= '';
		$orderby 	= '';
		$where 		= "";
		$fields_show = '';
				
		$join_clause_field = array ();
		$join_clause_table = array ();
		$field_temp = array();
		$subwhere = array ();		
		$where_clause = array();		
		
		$join_clause_table['rs'] =  "\n INNER JOIN #__users as rs ";
		$join_clause_field['rs'] = " ON rs.id=a.user_id and rs.block=0";		
		
		if(!checkPermission('view_list_resumes')){
			$request_temp = array();
		}
		else{
			$request_temp = $request;
			
			if($search){
	        	$subwhere [] .= " (rs.username LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
	        	 					" OR rs.email LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
	        						")";
	        }
		}
		
		JB_Build_where($join_clause_table, $join_clause_field, $field_temp, $where_clause, $this->_fieldListEdit, $filter_field_keys, $request_temp, $search, $subwhere);			
				
		if ($filter_order) {			
			if ($orderby)	$orderby .= ',';
			$orderby .= $filter_order . ' ' . $filter_order_Dir ;
		
		} elseif (! $order) {
			$orderby = " a.id Desc";
		}
		
		if($field_temp){
			$fields_show = ', '. implode(', ', $field_temp);	
		}
		
		foreach ($join_clause_table as $j=>$table){
			$join .= "\n $table ";
			if(isset($join_clause_field[$j])){
				$join .= $join_clause_field[$j];
			}
		}
			
		if ($where_clause) {
			$where = ' AND ' .implode(' AND ', $where_clause);
		}
			
		/* Count items */
		$query = "SELECT count(distinct a.id) ".
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more;	
		
		$db->setQuery ( $query );//echo $db->getQuery();exit;
		$total = $db->loadResult ();
		
		jimport ( 'joomla.html.pagination' );
		require_once (JPATH_SITE . DS . 'components' . DS . 'com_jajobboard' . DS . 'helper' . DS . 'japagination.php');
		$this->_pagination = new JAPagination ( $total, $limitstart, $limit );
		
		/* Get all items */
		$query = "SELECT distinct a.id, a.* $fields_show" . 
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more.
					"\n ORDER BY ". $orderby . ', a.id desc';
		$db->setQuery ( $query, $limitstart, $limit );//echo $db->getQuery();exit;
						
		$items = $db->loadObjectList ();
		
		if ($items) {
			foreach ( $items as $k => $job ) {
				if (isset($job->id)){									
					if ($this->_fieldList) {
							foreach ( $this->_fieldList as $field ) {
								
								$job->{$field->field_name} = JFilterInput::_decode ( $job->{$field->field_name} );
									
								if ($field->field_type == 'TEXTFIELD'){
									$job->{$field->field_name} = JFilterInput::clean ( $job->{$field->field_name} );
								}							
	
								
								if ($field->is_referred > 0 && $job->{$field->field_name}) {
									
									
									$values = explode(',', $job->{$field->field_name});
									foreach ($values as $i=>$v){
										$values[$i] = $db->Quote($v);	
									}
									$values = implode(',', $values);
									if(!$values) $values = 0;
									$sql = "SELECT {$field->referred_value} ".
											"\n FROM #__{$field->referred_table} ".
											"\n WHERE {$field->referred_key} in ($values)";
									$db->setQuery ( $sql );
									$result = $db->loadResultArray ();
									if ($result) {
										$job->{$field->field_name} = implode(', ', $result);
									}
									else{
										$job->{$field->field_name} = '';
									}
									
									
								} elseif (in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) ) && $job->{$field->field_name}) {
									
									$values = explode(',', $job->{$field->field_name});
									foreach ($values as $i=>$v){
										$values[$i] = $db->Quote($v);	
									}
									$values = implode(',', $values);
									$field_id = $field->table_name . '_' . $field->field_name;
									
									$sql = "SELECT text ".
											"\n FROM #__ja_codes ".
											"\n WHERE value in ($values) and field_id='$field_id' ";
																	
									$db->setQuery ( $sql );
									$result = $db->loadResultArray ();
									
									if ($result) {
										$job->{$field->field_name} = implode(', ', $result);
									}
									else{
										$job->{$field->field_name} = '';
									}
								}
						}
						
						$items [$k] = $job;
					}
					
					
				}
			}
		}		
		
		return $items;
	
	}
	
	/**
	 * @desc Get all fields that will be displayed on edit form
	 */
	function getEditFieldList($where = '') {
		if (! $this->_fieldListEdit) {
			$this->_fieldListEdit = getEditFieldList ( $this->_table_name, $where );
		}
		return $this->_fieldListEdit;
	}
	
	function getFieldList($where = '') {
		if (! $this->_fieldListEdit) {
			$this->_fieldList = getFieldList ( $this->_table_name, $where );
		}
		
		return $this->_fieldList;
	}
	
	/**
	 * Get field table instance
	 * @return JTable Configuration table object
	 */
	function &_getTable() {
		if ($this->_table == null) {
			$this->_table = &JTable::getInstance ( 'JA_Resumes', 'JobBoardTable' );
		}
		
		return $this->_table;
	}
	
	/**
	 * Get page navigator object
	 * @return 
	 */
	function &getPagination() {
		if ($this->_pagination == null) {
			$this->getItems ();
		}
		return $this->_pagination;
	}
	
	/**
	 * Get configuration item
	 * @return JobboardTableJA_resumes Table object
	 */
	function getItem() {
		static $item;
		if (isset ( $item )) {
			return $item;
		}
		
		$table = & $this->_getTable ();
		//        var_dump($table);exit;
		// Load the current item if it has been defined
		$edit = JRequest::getVar ( 'edit', true );
		$cid = JRequest::getVar ( 'cid', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $cid, array (0 ) );
		$user_id = JRequest::getInt ( 'user_id', 0 );
		
		if ($cid [0] && $user_id) {
			$table->_tbl_key = 'user_id';
			$cid [0] = $user_id;
			$user = JFactory::getUser($user_id);
			if(!$user->id || $user->block){
				$cid = 0;
			}			
		} else {
			$table->_tbl_key = 'id';
		}
		
		if ($edit) {
			
			$table->load ( $cid [0] );
		
		}
		$item = $table;
		
		return $item;
	}
	
	/**
	 * Get configuration item
	 * @return JobboardTableJA_Jobs Table object
	 */
	function getItemView() {
		static $item;
		if (isset ( $item )) {
			return $item;
		}
		$cid = JRequest::getVar ( 'cid', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $cid, array (0 ) );
		$db = & JFactory::getDBO ();
		$user = &JFactory::getUser ();
		if (getCurrentUserType () == JBJOB_SEEKER_USER && ! $cid [0]) {
			$query = "SELECT r.*,u.username,u.name,u.email,u.params,u.usertype FROM #__ja_resumes as r".
					 "\n INNER JOIN #__users as u ON u.id=r.user_id".
					 "\n WHERE r.user_id = " . $user->id. ' and u.block=0';
					 
			$db->setQuery ( $query );
			$item = $db->loadObject ();
			return $item;
		}
		
		$item = $this->getItem ();
		
		if ($item->id) {
			if ($item)
				$this->increaseViews ();
		}
		return $item;
	
	}
	/** 
	 * Store configuration item
	 * @param array The post array
	 */
	function store( $needCheck = true ) {
		// Initialize variables
		global $jbconfig;
		$user = JFactory::getUser ();
		$row = & $this->getItem ();
		$temp_item = getItemByFieldName ( 'ja_resumes', 'user_id', $user->id );
		if (isset ( $temp_item [0]->id ) && $temp_item [0]->id != 0 && $temp_item [0]->id != '') {
			if (! isset ( $row->id ) && $row->id == 0 && $row->id == '')
				return $temp_item [0]->id;
		}
		$controller = 'jaresumes';
		$step = JRequest::getVar ( 'step', '' );
		$db = & JFactory::getDBO ();
		
		$post    = JRequest::get('request', JREQUEST_ALLOWRAW);
		if ($row->id == null || $row->id==0) {
			$newresume = 1;
			$row->approved = $jbconfig ['account']->get ( 'ca_needs_approved' ) == 1 ? 0 : 1;
		} else
			$newresume = 0;
		if (! $row->created_date)
			$post ['created_date'] = date ( "Y-m-d H:i:s" );
		foreach ( $post as $k => $value ) {
			if ($k != 'cid' && is_array ( $value )) {
				$post [$k] = implode ( ',', $value );
			}
			elseif(!is_array ( $value )){
				$post [$k] = trim($value);
			}
		}
		
		
		
		if ($row->id)
			$post['id'] = $row->id;
		if ($step != 'done') {
			if (! $row->bind ( $post )) {
				return false;
			}
			
			if ($row->id == null || $row->id == 0) {
				$newresume = 1;
				$row->approved = ( $jbconfig ['account']->get ( 'ca_needs_approved' ) == 1 ) ? 0 : 1;
			} else
				$newresume = 0;
						
			if ($row->id > 0) {
				$row->_tbl_key = 'id';
			}
			
			if ( $needCheck ){
				if ($row->spec_field) {
					if (! assign_spec_field ( $controller, $row ))
						return false;
				}
					
				if ($row->editor_field)
					assign_editor_field($row);
				
				if (!$this->checkData($row)){
				    return false;
			    }
			}
			
			if (! $row->store ()) {				
				return false;
			} else {
				
				if ($newresume && $jbconfig ['emails']->get ( 'enabled' )) {
					$this->jobSeekerMailSignUp ( $row );
				}
			}
					
			return $row->id;
		} else {
			//            $query = "UPDATE #__ja_resumes SET posted=1 WHERE id = ".$row->id;
			//            $db->setQuery($query);
			//            return $db->query();
			return true;
		}
		
		return $row->id;
	}
	
	
	function checkData()
	{
		global $jbconfig;
		$user = JFactory::getUser ();
		$row = & $this->getItem ();
		$temp_item = getItemByFieldName ( 'ja_resumes', 'user_id', $user->id );
		if (isset ( $temp_item [0]->id ) && $temp_item [0]->id != 0 && $temp_item [0]->id != '') {
			if (! isset ( $row->id ) && $row->id == 0 && $row->id == '')
				return $temp_item [0]->id;
		}
		$controller = 'jaresumes';
		$step = JRequest::getVar ( 'step', '' );
		$db = & JFactory::getDBO ();
		
		$post    = JRequest::get('request', JREQUEST_ALLOWRAW);
		if ($row->id == null) {
			$row->approved = $jbconfig ['account']->get ( 'ca_needs_approved' ) == 1 ? 0 : 1;
		} 
		if (! $row->created_date)
			$post ['created_date'] = date ( "Y-m-d H:i:s" );
		foreach ( $post as $k => $value ) {
			if ($k != 'cid' && is_array ( $value )) {
				$post [$k] = implode ( ',', $value );
			}
		}
		if (! $row->bind ( $post )) {
			return false;
		}
		
		if ($row->spec_field) {
			if (! assign_spec_field ( $controller, $row ))
				return false;
		}
		
		if ($row->editor_field)
			assign_editor_field($row);
		
		if (! $row->check ()) {
			return false;
		}
		
		return $row;
	}
	/**
	 * Approve/Unapprove the resumes 
	 * 
	 */
	function approved($task = 'approved') {
		global $mainframe;
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		
		$table_name = 'ja_resumes';
		$is_approved = ($task == 'approved') ? 1 : 0;
		
		if ($table_name) {
			
			$query = "UPDATE #__$table_name SET is_approved = $is_approved WHERE id = " . implode ( " OR id = ", $cid );
			$db = &JFactory::getDBO ();
			$db->setQuery ( $query );
			
			return $db->query ();
		}
		return false;
	}
	
	/**
	 * Publish/Unpublish the resumes
	 * 
	 */
	function published($task = 'published') {
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		
		$is_published = $task == 'published' ? 1 : 0;
		
		$query = "UPDATE #__ja_resumes SET is_published = $is_published WHERE id = " . implode ( " OR id = ", $cid );
		$db = &JFactory::getDBO ();
		$db->setQuery ( $query );
		
		return $db->query ();
	}
	
	/**
	 * Publish/Unpublish the resumes
	 * 
	 */
	function activate($task) {
		
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		$field = JRequest::getVar ( 'field', "", 'post', 'cmd' );
		$table_name = JRequest::getVar ( 'table_name', "", 'post', 'cmd' );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		
		$active = $task == "activate" ? 1 : 0;
		
		if ($field == "is_starred") {
			$shortlistmd = JController::_createModel ( JBPREFIX . "ShortList", "JobBoardModel" );
			$shortlistmd->starred ( $task == "activate" ? "starred" : "unstarred" );
		} else if ($table_name && $field) {
			$query = "UPDATE #__$table_name SET $field = $active WHERE id = " . implode ( " OR id = ", $cid );
			
			$db = &JFactory::getDBO ();
			$db->setQuery ( $query );
			return $db->query ();
		}
		return false;
	}
	
	function increaseViews() {
		$item = $this->getItem ();
		$user = &JFactory::getUser ();
		if ($user->id != $item->user_id) {
			if (! isset ( $item->views ) || $item->views == null)
				$views = 1;
			else
				$views = $item->views + 1;
			$query = "UPDATE #__ja_resumes SET views = '" . $views . "' WHERE id  = " . $item->id;
			$db = &JFactory::getDBO ();
			$db->setQuery ( $query );
			$db->query ();
		}
	}
	
	/**
	 * Remove field record
	 * @return Number of removed records
	 */
	function remove($task = 'remove') {
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		JArrayHelper::toInteger ( $cid );
		
		$user = &JFactory::getUser ();
		if ($cid [0] && getCurrentUserType () == JBJOB_SEEKER_USER) {
			if ($task == 'remove') {
				// Remove attachment
				$item = $this->_getTable ();
				$item->load ( $cid [0] );
				if ($item->attachment) {
					JFile::delete ( JPATH_COMPONENT . DS . "uploaded" . DS . "resumes" . DS . $item->attachment );
				}
				
				$query = "DELETE FROM #__ja_resumes WHERE user_id = " . (int)$user->id . " AND id = " . (int)$cid [0];
				
				$db = &JFactory::getDBO ();
				$db->setQuery ( $query );
				return $db->query ();
			}
		}
		return false;
	}
	
	function checkMailData($mail_data) {
		if (! $mail_data ['youremail']) {
			JError::raiseWarning ( 1, JText::_ ( 'From email address must be not empty!' ) );
			return false;
		}
		if (! $mail_data ['friendemail']) {
			JError::raiseWarning ( 1, JText::_ ( 'Receive email address must be not empty!' ) );
			return false;
		}
		if (! $mail_data ['subject']) {
			JError::raiseWarning ( 1, JText::_ ( 'Email Subject must be not empty!' ) );
			return false;
		}
		return true;
	}
	
	function resumeMailSendFriend($resume_id, $emailtemplate = 'ResumeMailSendFriend') {
		$emailConfig = JobBoardConstant::getEmailConfig ();
		$user = JFactory::getUser ();
		$friendemail = JRequest::getVar ( 'friendemail' );
		$subject = JRequest::getVar ( 'subject' );
		$message = JRequest::getVar ( 'message', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		$mail_data = array ();
		$mail_data ['youremail'] = $user->email;
		$mail_data ['friendemail'] = $friendemail;
		$mail_data ['subject'] = $subject;
		$mail_data ['message'] = $message;
		if (! $this->checkMailData ( $mail_data ))
			return false;
		
		$friendemail = JRequest::getVar ( 'friendemail' );
		$arr_link = array ();
		$arr_link ['ja_resumes'] = $resume_id;
		$arr_link ['users'] = $user->id;
		$arr_link ['friend_mail'] = $friendemail;
		$subject = JRequest::getVar ( 'subject' );
		
		$message = JRequest::getVar ( 'message', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		$mail = get_EmailTemplate ( $arr_link, $emailtemplate, $message );
		
		if ($mail) {
			if (! $mail->EmailFromAddress)
				$mail->EmailFromAddress = $emailConfig ['fromemail'];
			if (! $mail->EmailFromName)
				$mail->EmailFromName = $emailConfig ['fromname'];
			if (! $subject)
				$subject = $mail->subject;
			if ($mail_data ['youremail'])
				$mail->EmailFromAddress = $mail_data ['youremail'];
			$result = sendMail ( $friendemail, 'My friend', $subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
			return $result;
		} else {
			JError::raiseWarning ( 0, JText::_ ( 'Email template system was not found! Please contact to Administrator!' ) );
			return false;
		}
	}
	function sendtojobseekerme($resume_id, $emailtemplate = 'ResumeMailSendJobseekerMe') {
		$emailConfig = JobBoardConstant::getEmailConfig ();
		$jobseeker_id = JRequest::getVar ( 'user_id' );
		$user = JFactory::getUser ( $jobseeker_id );
		
		$friendemail = $user->email;
		$user = JFactory::getUser ();
		
		$message = JRequest::getVar ( 'message', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		$arr_link = array ();
		$arr_link ['ja_resumes'] = $resume_id;
		$arr_link ['users'] = $user->id;
		$arr_link ['friend_mail'] = $friendemail;
		
		$message = JRequest::getVar ( 'message', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		$mail = get_EmailTemplate ( $arr_link, $emailtemplate, $message );
		
		if ($mail) {
			if (! $mail->EmailFromAddress)
				$mail->EmailFromAddress = $emailConfig ['fromemail'];
			if (! $mail->EmailFromName)
				$mail->EmailFromName = $emailConfig ['fromname'];
			if (! $subject)
				$subject = $mail->subject;
			if ($mail_data ['youremail'])
				$mail->EmailFromAddress = $mail_data ['youremail'];
			$result = sendMail ( $user->email, $user->name, $subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
			return $result;
		}
		{
			JError::raiseWarning ( 0, JText::_ ( 'Email template system was not found! Please contact to Administrator!' ) );
			return false;
		}		
	}
	function sendtojobseeker($resume_id, $emailtemplate = 'ResumeMailSendJobseeker') {
		$emailConfig = JobBoardConstant::getEmailConfig ();
		$jobseeker_id = JRequest::getVar ( 'user_id' );
		$user = JFactory::getUser ( $jobseeker_id );
		
		$friendemail = $user->email;
		$user = JFactory::getUser ();
		
		$subject = JRequest::getVar ( 'subject' );
		$message = JRequest::getVar ( 'message', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		$mail_data = array ();
		$mail_data ['youremail'] = $user->email;
		$mail_data ['friendemail'] = $friendemail;
		$mail_data ['subject'] = $subject;
		$mail_data ['message'] = $message;
		if (! $this->checkMailData ( $mail_data ))
			return false;
		
		$arr_link = array ();
		$arr_link ['ja_resumes'] = $resume_id;
		$arr_link ['users'] = $user->id;
		$arr_link ['friend_mail'] = $friendemail;
		$subject = JRequest::getVar ( 'subject' );
		
		$message = JRequest::getVar ( 'message', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		$mail = get_EmailTemplate ( $arr_link, $emailtemplate, $message );
		
		if ($mail) {
			if (! $mail->EmailFromAddress)
				$mail->EmailFromAddress = $emailConfig ['fromemail'];
			if (! $mail->EmailFromName)
				$mail->EmailFromName = $emailConfig ['fromname'];
			if (! $subject)
				$subject = $mail->subject;
			if ($mail_data ['youremail'])
				$mail->EmailFromAddress = $mail_data ['youremail'];
			$result = sendMail ( $friendemail, 'My friend', $subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
			return $result;
		}
		{
			JError::raiseWarning ( 0, JText::_ ( 'Email template system was not found! Please contact to Administrator!' ) );
			return false;
		}
	}
	
	function resumeMailSendMe($resume_id, $emailtemplate = 'ResumeMailSendMe') {
		$emailConfig = JobBoardConstant::getEmailConfig ();
		$user = JFactory::getUser ();
		$friendemail = JRequest::getVar ( 'friendemail' );
		$arr_link = array ();
		$arr_link ['ja_resumes'] = $resume_id;
		$arr_link ['users'] = $user->id;
		$arr_link ['friend_mail'] = $friendemail;
		$subject = JRequest::getVar ( 'subject' );
		
		$message = JRequest::getVar ( 'message', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$mail = get_EmailTemplate ( $arr_link, $emailtemplate, $message );
		if (! $mail->EmailFromAddress)
			$mail->EmailFromAddress = $emailConfig ['fromemail'];
		if (! $mail->EmailFromName)
			$mail->EmailFromName = $emailConfig ['fromname'];
		$user = JFactory::getUser ();
		if ($mail) {
			sendMail ( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
		}
	}
	
	function jobSeekerMailSignUp($resume, $emailtemplate = 'JobSeekerMailSignUp') {
		global $jbconfig;
		$user = JFactory::getUser ($resume->user_id);
		$arr_link = array ();
		$arr_link ['ja_resumes'] = $resume->id;
		$arr_link ['users'] = $user->id;
		$emailConfig = JobBoardConstant::getEmailConfig ();
		$mail = get_EmailTemplate ( $arr_link, $emailtemplate );
		
		if ($mail) {
			if (! $mail->EmailFromAddress)
				$mail->EmailFromAddress = $emailConfig ['fromemail'];
			if (! $mail->EmailFromName)
				$mail->EmailFromName = $emailConfig ['fromname'];
			$result = sendMail ( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
			return $result;
		} else {
			JError::raiseWarning ( 0, JText::_ ( 'Email template system was not found! Please contact to Administrator!' ) );
			return false;
		}
	}
	
	function download() {
	    // Get current URI
        $uri = JFactory::getURI();
        $url = $uri->toString();
        $url = base64_encode($url);
	    // Check download Permission
	    $msg = checkDownloadPermission(array("Employer User", "Job Seeker User"));
	    if( $msg != "" ){
	       return false;	       
	    }
	    
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		$n = count ( $cid );
		$fieldname = JRequest::getVar('field_name', 'file_attachment');
		JArrayHelper::toInteger ( $cid );
		
		$item = $this->getItem ();		
		$file_name = explode ( '/', $item->{$fieldname} );
		if ($item->{$fieldname}) {
			$file = JPATH_SITE . DS . str_replace ( '/', '\\', $item->{$fieldname} );
			if (file_exists ( str_replace ( '/', '\\', $file ) ))
				$file = str_replace ( '/', '\\', $file );
			else
				$file = str_replace ( '\\', '/', $file );
			
			if ( ! file_exists($file) ){
        		echo JText::_("<script language='javascript'> alert('".JText::_("File not found on the Server")."'); </script>");
        		return false;
        	}
        	
            header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="'.substr ( $file_name [count ( $file_name ) - 1], 14 ) .'"');
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    ob_clean();
		    flush();
		    readfile($file);
		}
		return true;
	}
	
	function getHotResumeOptions() {
		$db = &JFactory::getDBO ();
		$query = "SELECT id, ckeytitle, ckey, cvalue FROM #__ja_config WHERE ckey LIKE 'HOTJOB%' ORDER BY ckey";
		$db->setQuery ( $query );
		$cfg = $db->loadObjectList ();
		return $cfg;
	}
	
	function remove_attach() {
		remove_attach ( 'ja_resumes' );
	
	}
	function getItemNotes($items) {
		$temp = array ();
		for($i = 0; $i < count ( $items ); $i ++)
			$temp [] = $items [$i]->id;
		$item_list = implode ( ',', $temp );
		if ($item_list) {
			$where = " and item_id IN ($item_list) and note_type='ja_resumes'";
			$note_list = getItemNotes ( $where );
			
			return $note_list;
		}
		return '';
	}
	function geItemView_List() {
		$arr_username = JRequest::getVar ( 'cid' );
		$db = JFactory::getDBO ();
		if (count ( $arr_username ) > 0) {
			
			if (JRequest::getVar ( 'pre_layout', 'jaview' ) == 'jalist') {
				$limit = 5;
				$limitstart = 0;
			} else {
				$limit = JRequest::getVar ( 'limit', 5 );
				$limitstart = JRequest::getVar ( 'limitstart', 0 );			
			}	
			
			if(!intval($arr_username[0])){
				foreach ($arr_username as $username){
					$username = str_replace("()", ".", $username);
					$arr_str_username[] = "'$username'";
				}
				$user_ids = getUserIds(implode(',', $arr_str_username));
				if($user_ids) $user_ids = implode(',', $user_ids);
				else return ;
				
				$query = "SELECT * FROM #__ja_resumes WHERE user_id IN ($user_ids) LIMIT $limitstart , $limit";
			}
			else{
				$str_ids = implode(',', $arr_username);
				$query = "SELECT * FROM #__ja_resumes WHERE id IN ($str_ids) LIMIT $limitstart , $limit";				
			}
			
			$db->setQuery ( $query );
			$item_views = $db->loadObjectList ();
			jimport ( 'joomla.html.pagination' );
			require_once (JPATH_SITE . DS . 'components' . DS . 'com_jajobboard' . DS . 'helper' . DS . 'japagination.php');
			$this->_pagination = new JAPagination ( count ( $item_views ), $limitstart, $limit );
			
			return $item_views;
		} elseif (JRequest::getVar ( 'layout' ) == 'jaview' || JRequest::getVar ( 'layout' ) == 'myresumes') {
			$user = JFactory::getUser ();
			$query = "SELECT * FROM #__ja_resumes WHERE user_id = ".(int)$user->id;
			$db->setQuery ( $query );
			$item_views = $db->loadObjectList ();
			jimport ( 'joomla.html.pagination' );
			require_once (JPATH_SITE . DS . 'components' . DS . 'com_jajobboard' . DS . 'helper' . DS . 'japagination.php');
			$this->_pagination = new JAPagination ( 1, 0, 1 );
			return $item_views;
		} else
			return '';
	}
	
	function getNoteForItemView($where) {
		$db = JFactory::getDBO ();
		$query = "SELECT * FROM #__ja_notes WHERE 1=1  $where";
		$db->setQuery ( $query );
		$result = $db->loadObjectList ();
		if (count ( $result ) > 0) {
			$note_list = array ();
			foreach ( $result as $note ) {
				$note_list [$note->item_id] = $note;
			}
			return $note_list;
		} else
			return '';
	}

}
?>